// import utils from 'utils'
import { queryDictByCodes, queryAllCompany, queryAllCity } from 'api/common'
import utils from 'utils'

const state = {
  dictList: [], // 字典
  allCity: [],
  allCompany: []
}

const mutations = {
  SET_DICTLIST: (state, val) => {
    state.dictList = val
  },
  SET_ALLCITY: (state, val) => {
    state.allCity = val
  },
  SET_ALLCOMPANY: (state, val) => {
    state.allCompany = val
  }
}

const actions = {
  /**
   * 获取字典数据
   */
  getDict({ commit }, params) {
    return new Promise((resolve, reject) => {
      const curParams = {
        dicCode: params.dicCode
      }
      queryDictByCodes(curParams)
        .then(val => {
          const dictObj = {}
          dictObj[val.dicCode] = {
            label: val.name,
            value: val.dicCode
          }
          commit('SET_DICTLIST', dictObj)
          resolve(dictObj)
        })
        .catch(err => {
          reject(err)
        })
    })
  },
  /**
   *  获取所以区域
   * @param {*} param0
   * @returns
   */
  getAllCity({ commit }) {
    return new Promise((resolve, reject) => {
      queryAllCity()
        .then(res => {
          const curList = res.map(val => ({
            label: val.name,
            value: val.code,
            longitude: val.longitude,
            latitude: val.latitude
          }))
          commit('SET_ALLCITY', curList)
          utils.setStore('cityList', curList)
          resolve(curList)
        })
        .catch(err => {
          reject(err)
        })
    })
  },
  /**
   * 获取所以企业
   * @param {*} param
   * @returns
   */
  getAllCompany({ commit }) {
    return new Promise((resolve, reject) => {
      queryAllCompany({
        rows: 1,
        offset: 999
      })
        .then(res => {
          const companyList = res.data.map(val => ({ label: val.companyName, value: val.id }))
          commit('SET_ALLCOMPANY', companyList)
          utils.setStore('companyList', companyList)
          resolve(companyList)
        })
        .catch(err => {
          reject(err)
        })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
